<?php
/**
 * Created by PhpStorm.
 * User: N
 * Date: 2017/12/13
 * Time: 15:17
 */
namespace common\models;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use common\models\Attachment;
use common\models\Branch;
use common\models\User;
use common\models\Notice;
use common\models\Agenda;
use yii\helpers\ArrayHelper;
use backend\components\Utools;

/**
 * This is the model class for table "category".
 *
 * @property string $catid
 * @property string $siteid
 **/
class Meeting extends ActiveRecord
{
     /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%meeting}}';
    }



    /**
    * 验证规则
    */
    public function rules()
    {
        return [
                    
            [['title','mtype'],'required','message'=>'不能为空'],
            [['attaches','branch_id','latid','lonid'],'string'],    
            [['begin_time','end_time','isadmin'],'number'], 
            [['create_username','summary','content','uids'],'default'], 
            [['create_uid','create_time'],'number'],    
            [['not_join_uid','host','record','place','themeid','mform','plan'],'default'],
        ];
    }

    public function init(){
        // $this->updateStatus();
    }

    public function afterFind(){
        // $this->updateStatus();
    }

    public function beforeSave($insert){
        if($insert){
            if(Yii::$app->id=='app-backend')//管理后端创建
            {
                $this->isadmin=1;
            }
            else
            {
                $this->isadmin=0;
            }

            $this->status=0;
            $this->no = date('Ymd',$this->begin_time);
            $this->create_time=time();
            //获取参会人员信息
           $this->branch_id = trim($this->branch_id,',');
           $join_members = User::find()->where('branch_id in ('.$this->branch_id.')')->select('id')->asArray()->all();
           $this->join_uid ='';//初始化参会人员id
           if($join_members){
               //$join_uid ='';
               foreach($join_members as $v){
                   $join_uid[] =$v['id'];
               }
               $str=implode(',',$join_uid);
               $str=','.$str.',';
               $this->join_uid = $str;
           }

//            $this->join_uid = '1,2,3,4,5';//临时测试
            $this->not_join_uid ='';//临时测试
            //插入时补充操作
            //$this->inputtime = time();
        }else{
            //修改时补充操作
            // print_r($this->not_join_uid);
            // exit;

            //=============================================================================根据是否为计划
            if(!empty($this->attaches)){//如果会议资料不为空 
                if(!$this->plan){
                    $this->status = 1;//如果未计划会议 标记为已完成 
                }
                else{
                    if(time()>$this->begin_time&&time()<$this->begin_time+86400*5){
                       $this->status = 1;//如果是已计划会议 在会议开始后且不超过截止日期 标记为已完成 
                    }
                }

            }
           $this->no = date('Ymd',$this->begin_time);//保存会议编号

            //=============================================================================

            $not_join_uid = explode(',',$this->not_join_uid);//会议缺席人员id
            $branch_id = explode(',',trim($this->branch_id,','));//会议应参加支部id

            $meet_uid =  User::find()->select(['id'])->where(['branch_id'=>$branch_id])->asArray()->all();//会议应到人员id
            $meet_uid = ArrayHelper::getColumn($meet_uid,'id');
            $join_uid_arr =  array_diff($meet_uid, $not_join_uid);//会议实到人员id
            $join_uid = implode(',',$join_uid_arr);
            $this->join_uid = ','.$join_uid.',';
        }
      
        return true;

    }

    public function afterSave($insert)
    {
        if($insert)
        {
            /**通知以及日程创建 *//* $members = ['branch_id'=>[0=>['id'=>10,'realname'=>'测试',...]]]*/
            $members=$this->getBranchusers(0);
            if($this->begin_time)
            {
                $dates=Utools::bDates($this->begin_time,$this->end_time);
            }
            foreach($members as $member)
            {
                if($member){
                    foreach($member as $m){
                        $notice=new Notice();
                        $notice->title=$this->title;
                        $notice->content=$this->content;
                        $notice->from_id=$this->create_uid;
                        $notice->isadmin=$this->isadmin;
                        $notice->to_id=$m->id;
                        $notice->type_id=1;//暂定1
                        $notice->save();

                        /**日程添加 */
                        if($this->begin_time)
                        {
                            $i=0;
                            foreach($dates as $date)
                            {
                                $agenda=new Agenda();
                                $runtime=strtotime("+$i day",$this->begin_time);
                                $agenda->title=$this->title;
                                $agenda->content=$this->summary;
                                $agenda->run_time=$runtime;
                                $agenda->aid=$this->mid;
                                $agenda->bid=$this->branch_id;
                                $agenda->model='Meeting';
                                $agenda->isadmin=$this->isadmin;
                                $agenda->uid=$m->id;
                                $agenda->save();
                                //$agenda->add_time=time();

                                $i++;
                            }
                        }
                    }
                }

            }
        }
        return true;
    }

    /**
     * 获取附件列表
     */
    public function getAttachlist()
    {
        if($this->attaches)
        {
            $attachids=explode(',',$this->attaches);
            foreach($attachids as $tt)
            {
                if($tt)
                    $temps[]=$tt;
            }
            $astr=implode(',',$temps);
            $attaches=Attachment::find('')->where("status=0 and aid in ({$astr})")->orderBy('aid desc')->all();
            return $attaches;
        }
        else
        {
            return [];
        }
    }

    /**
     * 获取未参加用户
     * $bid =0 所有用户 $bid 按支部获取
     */
    public function getNotusers($bid=0)
    {
        if($this->not_join_uid)
        {

            $users=[];
            if($bid)
            {
                $users=User::find()->where("id in({$this->not_join_uid}) and branch_id = {$bid}")->orderBy(' id asc ')->all();
                return $users;
            }
            else
            {
                if($this->branch_id)
                {
                    $branch_array=explode(',',$this->branch_id);
                    foreach($branch_array as $branch)
                    {
                        $users[$branch]=User::find()->where("id in({$this->not_join_uid}) and branch_id = {$branch}")->orderBy(' id asc ')->all();
                    }
                }
                return $users;
            }
            
        }
        else
        {
            return [];
        }
    }
    /**
     * 获取参与支部信息
     */
    public function getBranches()
    {

        if($this->branch_id)
        {
            $this->branch_id = trim($this->branch_id,',');
            $branches=Branch::find('')->where("status=0 and id in ({$this->branch_id})")->orderBy('id desc')->all();
            return $branches;
        }
        else
        {
            return '';
        }

    }

     /**
     * 获取参与支部成员列表
     * $bid 支部id
     * $returntype  object 返回用户对象数组  string  返回字符串 形式: 李滨,张子扬,杨文峰
     */
    public function getBranchusers($bid=0,$returntype='object')
    {

        if($this->branch_id)
        {
            if($bid)//获取某个支部成员
            {
                if($returntype=='object')
                {
                    $members=User::find('')->where("status=0 and branch_id =$bid ")->orderBy('id desc')->all();
                    return $members;
                }
                else
                {
                    $members=User::find('realname')->asArray()->where("status=0 and branch_id =$bid ")->orderBy('id desc')->all();
                    foreach($members as $mem)
                    {
                        $memarray[]=$mem['realname'];
                    }
                    return implode(',',$memarray);
                }
                
            }
            else//获取所有参会成员
            {
                if($returntype=='object')
                {

                    if($this->branch_id)
                    {
                        $branch_array=explode(',',$this->branch_id);
                        foreach($branch_array as $branch)
                        {
                            if($branch)
                                $members[$branch]=User::find()->select('id')->where(" branch_id = {$branch} ")->orderBy(' id asc ')->all();
                        }
                    }

                    return $members;
                }
                else
                {
                    $members=User::find('realname')->asArray()->where("status=0 and branch_id in ({$this->branch_id}) ")->orderBy('id desc')->all();
                    
                    foreach($members as $mem)
                    {
                        $memarray[]=$mem['realname'];
                    }
                    return implode(',',$memarray);
                }
               
            }
            
        }
        else
        {
            return '';
        }

    }

        /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'status' => '状态',
            'summary' => '摘要',
            'content' => '内容',
            'begin_time' =>'开始时间',
            'end_time' =>'结束时间',
            'attaches' =>'会议资料',
            'branch_id'=> '党支部',
            'isadmin'=> '是否管理员发起',
            'place'=>'会议地点',
            'host'=>'主持人',
            'record'=>'记录人',
            'mform'=>'会议形式',
        ];
    }



    //获取会议类型
    public function getMeetType(){

        switch ($this->mtype) {
            case 1:
                return '支部党员大会';
                break;
            case 2:
                return '党支部委员会';
                break;
            case 3:
                return '党小组会';
                break;
            default:
                return '未定义';
                break;
        }
    }



    //获取会议形式
    public function getMeetForm(){

        switch ($this->mform) {
            case 1:
                return '党课';
                break;
            case 2:
                return '主题党日';
                break;
            default:
                return '未定义';
                break;
        }
    }



    //获取会议状态
    public function getStatusType(){

        $deadline = $this->begin_time+86400*5;//截止时间
 
        switch ($this->status) {
            //动态状态
            case 0:
                if(time()>$this->begin_time&&time()<$this->end_time){
                    return ['value'=>'进行中','status'=>'success'];
                }
                elseif(time()>$this->begin_time&&time()<=$deadline){
                	return ['value'=>'已延期','status'=>'warning'];
                }
                elseif(time()>$deadline){
                    if($this->plan){
                	    return ['value'=>'已延误','status'=>'danger'];
                    }
                    else{
                        return ['value'=>'已延期','status'=>'warning'];
                    }
                }
                else{
                    if($this->plan){
                        return ['value'=>'已计划','status'=>'info'];
                    }
                    else{
                        return ['value'=>'未开始','status'=>'mute']; 
                    }
                }
                break;
            case 1:
                return ['value'=>'已完成','status'=>'success'];
                break;
            case 2:
                return ['value'=>'已延期','status'=>'warning'];
                break;
            case 3:
                return ['value'=>'已延误','status'=>'danger'];
                break;
            case -1:
                return ['value'=>'删除','status'=>'danger'];
                break;
            default:
                return '未定义';
                break;
        }
    }


    public function updateStatus(){
        // if(time()>$this->begin_time&&time()<$this->end_time){
        //     $this->status = 3;
        // }
    }


}